<template>
  <div id="app">
    <router-view />
  </div>
</template>
<script>
import { mapGetters } from 'vuex'
import * as CONSTANTS from '@/constants/index'
import * as UTILS from '@/utils/index'

export default {
  props: {},
  components: {},
  data() {
    return {
      iOSUserId: null,
      androidUserId: null,
      iOSBabyId: null,
      androidBabyId: null,
    }
  },
  async created() {},
  computed: {
    ...mapGetters(['common', 'user']),
    isDev() {
      return process.env.NODE_ENV === CONSTANTS.VAR_NODE_ENV_DEV
    },
    //当前用户ID
    userId() {
      if (this.isDev) return CONSTANTS.VAR_USERID
      if (UTILS.isIOSDevice()) return this.iOSUserId
      return this.androidUserId
    },
    //当前宝宝ID
    babyId() {
      if (this.isDev) return CONSTANTS.VAR_BABYID
      if (UTILS.isIOSDevice()) return this.iOSBabyId
      return this.androidBabyId
    },
    curBabyData() {
      if (!this.user) return null
      return this.user.currentBabyData
    },
    isReady() {
      return (
        !!this.common && !!this.common.token && !!this.userId && !!this.babyId
      )
    },
  },
  async created() {
    await this.$store.dispatch(CONSTANTS.DISPATCH_GETASYNC_COMMONTOKEN)
  },
  async mounted() {
    if (!this.isDev && UTILS.isAndroidDevice()) await this.getAndroidData()
    if (!this.isDev && UTILS.isIOSDevice()) await this.getIOSData()

    await this.onInjectUmengEventTrack()
  },
  filters: {},
  watch: {
    async isReady(isReady) {
      if (!isReady) return
      //缓存userId
      this.$store.commit(
        CONSTANTS.COMMIT_UPDATE_USER_CURRENTUSERID,
        this.userId
      )
      const params = { userId: this.userId }
      await this.$store.dispatch(
        CONSTANTS.DISPATCH_GETASYNC_USERALLBABIES,
        params
      )

      if (window.location.href.indexOf('isShare') < 0) return
      let recordId = UTILS.getQueryStringValue('recordId')
      await this.$store.dispatch(CONSTANTS.DISPATCH_GET_RESULTBYITEMID, {
        recordId,
      })
    },
    babyId: {
      immediate: true,
      handler(v, prevVal) {
        if (v) this.$store.commit(CONSTANTS.COMMIT_UPDATE_USER_CURRENTBABYID, v)
      },
    },

    curBabyData: {
      immediate: true,
      deep: true,
      handler(v) {
        if (!v) return
        const { birthday } = v
        const toNumBirthday = UTILS.getGrowAge(birthday)
        const dayDuration = UTILS.getDateDuration(birthday)
        const { year, month } = toNumBirthday
        this.$store.commit(
          CONSTANTS.COMMIT_UPDATE_USER_BABYTRANSFORMEDBIRTHDAY,
          toNumBirthday
        )

        const ageStage = UTILS.getAgeStage(year, month)
        this.$store.commit(CONSTANTS.COMMIT_UPDATE_USER_BABYAGESTAGE, ageStage)
        this.$store.commit(
          CONSTANTS.COMMIT_UPDATE_USER_BABYAGEDATEDURATION,
          dayDuration
        )
      },
    },
  },
  methods: {
    async showLackBabyModal() {
      const dialog = await this.$createDialog(
        () => import('@/views/Transition/modules/LackBabyModal.vue'),
        {
          destroyOnClose: true,
          on: {
            close: (v) => {
              dialog.close()
              if (UTILS.isIOSDevice())
                return window.webkit.messageHandlers.addBabys.postMessage(null)
              else return window.android.playCourse('addBabys', '')
            },
          },
        }
      )
    },
    getIOSData() {
      if (window.location.href.indexOf('isShare') > -1)
        return this.onShareInitData()
      window.webkit.messageHandlers.getUserInfo.postMessage(null)
      window.webkit.messageHandlers.getCurrentBaby.postMessage(null)
      window['getUserInfo'] = (res) => {
        this.iOSUserId = res.uid
      }
      window['getCurrentBaby'] = async (res) => {
        console.warn('getCurrentBaby - res')
        console.log(res)
        console.log('\n')

        if (!res || !res.babyId) this.showLackBabyModal()
        this.iOSBabyId = res.babyId
      }
    },
    getAndroidData() {
      if (window.location.href.indexOf('isShare') > -1)
        return this.onShareInitData()

      let userObj = window.android.getUserInfo()
      let babyObj = window.android.getCurrentBaby()
      if (!babyObj) this.showLackBabyModal()
      userObj = JSON.parse(userObj)
      babyObj = JSON.parse(babyObj)

      this.androidUserId = userObj.uid
      this.androidBabyId = babyObj.id
    },
    async onShareInitData() {
      let userId = UTILS.getQueryStringValue('userId')
      let babyId = UTILS.getQueryStringValue('babyId')

      UTILS.isIOSDevice()
        ? (this.iOSUserId = userId)
        : (this.androidUserId = userId)
      UTILS.isIOSDevice()
        ? (this.iOSBabyId = babyId)
        : (this.androidBabyId = babyId)
    },

    // 注入埋点初始化代码
    onInjectUmengEventTrack() {
      const script = document.createElement('script')
      script.src = CONSTANTS.URL_UMENG_EVENTTRACK
      script.language = 'JavaScript'
      document.body.appendChild(script)
    },
  },
}
</script>

<style lang="less" scoped></style>
<style>
* {
  user-select: none;
}
</style>
